package com.i.template.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.i.template.constant.RedisConstants;
import com.i.template.constant.ResponseResult;
import com.i.template.domain.FollowDO;
import com.i.template.domain.vo.FollowVO;
import com.i.template.domain.vo.UserVO;
import com.i.template.service.IFollowerService;
import com.i.template.util.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author lewis
 * @type class
 * @description
 * @since 2024/8/8
 */
@RestController
@RequestMapping("/follow/of")
@RequiredArgsConstructor
public class FollowerController {
    private final IFollowerService service;
    private final StringRedisTemplate redisTemplate;
    @GetMapping("/{id}")
    public ResponseResult<List<UserVO>> queryFollowById(@PathVariable Long id) {
        Long userId = UserHolder.getUser();
        Set<String> members = redisTemplate.opsForSet().members(RedisConstants.USER_FOLLOW_PREFIX + userId);
        if(members == null || members.isEmpty()) {
            List<UserVO> userVOS = service.queryFollowById(id);
            List<String> list = userVOS.stream().map(JSONUtil::toJsonStr).toList();
            String[] array = ArrayUtil.toArray(list, String.class);
            redisTemplate.opsForSet().add(RedisConstants.USER_FOLLOW_PREFIX + userId,array);
            return ResponseResult.ok(userVOS);
        }
        List<UserVO> list = members.stream().map(member -> JSONUtil.toBean(member, UserVO.class)).toList();
        return ResponseResult.ok(list);
    }
    @PostMapping
    public ResponseResult<Boolean> saveFollow(@RequestBody FollowVO followVO) {
        Long userId = UserHolder.getUser();
        redisTemplate.delete(RedisConstants.USER_FOLLOW_PREFIX + userId);
        return ResponseResult.judge(service.save(BeanUtil.copyProperties(followVO,FollowDO.class)));
    }
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> cancelFollowById(@PathVariable Long id) {
        Long userId = UserHolder.getUser();
        redisTemplate.delete(RedisConstants.USER_FOLLOW_PREFIX + userId);
        return ResponseResult.judge(service.removeById(id));
    }
}
